<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <meta name="author" content="Yb">
    <title>JQ拖拽图片上传</title>
    <script src="../js/jquery-3.1.1.js"></script>
    <style>
        div {
            width: 300px;
            height: 300px;
            border: 2px solid #aaa;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 26px;
        }
        
        img {
            max-width: 100%;
            max-height: 100%;
        }
        section{
            width: 100%;
            margin-top: 100px;
        }
    </style>
</head>

<body>
    <div>
        <span>拖到图片到这里</span>
        <img>
    </div>
    <button type="submit">上传</button>

    <section><a href="01-拖动图片上传.html" target="_blank">标准版</a></section>
</body>

</html>
<script>
    function ignoreDrag(ev) {
        ev.originalEvent.stopPropagation();
        ev.originalEvent.preventDefault();
    }

    $('div')
        .bind('dragenter', ignoreDrag)
        .bind('dragover', ignoreDrag)
        .bind('drop', drop);

    function drop(ev) {
        ignoreDrag(ev);
        var dt = ev.originalEvent.dataTransfer;
        var files = dt.files;
        var file = files[0];
        if (file.type.startsWith('image')) {
            // 加载图片
            $('img').attr('src', URL.createObjectURL(file));
            // 隐藏span标签
            $('span').hide();
        } else {
            alert('请上传图片类型，只支持图片上传');
        }
    }
    
</script>